<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" class="custom-dialog" width="80%">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="labelWidth"
        v-loading="formLoading"
        class="custom-form"
      >
        <el-form-item label="客户级别" prop="name" class="form-item">
          <el-input
            v-model.trim="formData.name"
            placeholder="请输入客户级别"
            class="custom-input"
          />
        </el-form-item>

        <el-form-item label="标签颜色" prop="bgColor" class="form-item">
          <div class="color-section">
            <div class="color-palette">
              <div
                :class="['color-item', { 'color-selected': item == formData.bgColor }]"
                v-for="(item, index) in defaultColors.slice(2)"
                :key="index + 'color'"
              >
                <span
                  @click="chooseBgColor(item)"
                  :style="{ background: item }"
                  class="color-span"
                ></span>
              </div>
            </div>
            <el-color-picker
              show-alpha
              :predefine="predefineColors"
              @change="bgPickerChange"
              class="custom-color-picker"
            />
          </div>
        </el-form-item>

        <el-form-item label="文字颜色" prop="textColor" class="form-item">
          <div class="color-section">
            <div class="color-palette">
              <div
                :class="['color-item', { 'color-selected': item == formData.textColor }]"
                v-for="(item, index) in [
                  defaultColors[1],
                  defaultColors[0],
                  ...[...[...defaultColors].slice(2, 6), ...[...defaultColors].slice(8)].reverse()
                ]"
                :key="index + 'color'"
              >
                <span
                  @click="chooseTextColor(item)"
                  :style="{ background: item }"
                  class="color-span"
                ></span>
              </div>
            </div>
            <el-color-picker
              show-alpha
              :predefine="predefineColors"
              @change="textPickerChange"
              class="custom-color-picker"
            />
          </div>
        </el-form-item>

        <el-form-item label="级别" prop="sort" class="form-item">
          <div class="level-input-wrapper">
            <el-input-number
              class="custom-input-number"
              :min="1"
              :max="100"
              :step="1"
              v-model="formData.sort"
              placeholder="请输入级别"
            />
            <span class="level-tips">数值越大,级别越高</span>
          </div>
        </el-form-item>

        <el-form-item label="预览" class="form-item preview-item">
          <div class="preview-wrapper">
            <EntTag
              :content="formData.name"
              :bgColor="formData.bgColor"
              :textColor="formData.textColor"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="delForm"
          type="danger"
          v-hasPermi="['crm:label:delete']"
          class="delete-btn"
          v-if="formType == 'update'"
        >
          删 除
        </el-button>
        <div class="footer-right">
          <el-button @click="submitForm" type="primary" :disabled="formLoading" class="submit-btn">
            确 定
          </el-button>
          <el-button @click="dialogVisible = false" class="cancel-btn">取 消</el-button>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as customerTagApi from '@/api/crm/customerTagConfig/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  name: undefined,
  bgColor: 'rgba(2, 129, 252, 1)',
  textColor: '#ffffff',
  sort: undefined,
  id: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '客户级别不能为空', trigger: 'blur' }],
  bgColor: [{ required: true, message: '标签颜色不能为空', trigger: 'blur' }],
  textColor: [{ required: true, message: '文字颜色不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '级别不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const defaultColors = ref([
  '#000000',
  '#ffffff',
  'rgba(2, 129, 252, 1)',
  'rgba(43, 151, 255, 1)',
  'rgba(80, 168, 252, 1)',
  'rgba(124, 190, 252, 1)',
  'rgba(255, 0, 0, 1)',
  'rgba(252, 50, 50, 1)',
  'rgba(255, 98, 98, 1)',
  'rgba(252, 143, 143, 1)',
  'rgba(255, 208, 0, 1)',
  'rgba(252, 214, 45, 1)',
  'rgba(254, 225, 97, 1)',
  'rgba(251, 232, 147, 1)'
])
const props = defineProps({
  moduleId: {
    type: Number
  }
})

// 响应式计算属性
const labelWidth = computed(() => {
  return window.innerWidth <= 768 ? '80px' : '100px'
})

const chooseBgColor = (color) => {
  formData.value.bgColor = color
}
const chooseTextColor = (color) => {
  formData.value.textColor = color
}
const bgPickerChange = (color) => {
  formData.value.bgColor = color
}
const textPickerChange = (color) => {
  formData.value.textColor = color
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type == 'update') {
    formData.value = await customerTagApi.getCustomerLevel(id)
  }
  formLoading.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    // data.moduleId = props.moduleId
    if (formType.value === 'create') {
      await customerTagApi.createLevelSet(data)
      message.success(t('common.createSuccess'))
    }
    if (formType.value === 'update') {
      await customerTagApi.updateLevelSet(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: undefined,
    bgColor: 'rgba(2, 129, 252, 1)',
    textColor: '#ffffff',
    sort: undefined,
    id: undefined
  }
  formRef.value?.resetFields()
}
/*删除*/
const delForm = () => {
  ElMessageBox.confirm('确定要删除当前标签吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await customerTagApi.deleteTag(formData.value.id)
      dialogVisible.value = false
      if (res) ElMessage.success('删除成功!')
      emit('success')
    })
    .catch(() => {})
}
</script>

<style scoped>
/* 对话框样式 */
.custom-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.custom-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: white;
  padding: 20px 24px;
  border-radius: 12px 12px 0 0;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f7ff;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #fafbfc;
}

/* 表单容器 */
.form-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.custom-form {
  margin: 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  line-height: 1.5;
}

/* 输入框样式 */
.custom-input {
  width: 100%;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 颜色选择区域 */
.color-section {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.color-palette {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.color-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
  border: 2px solid transparent;
  border-radius: 6px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.color-item:hover {
  border-color: #0052cc;
  transform: scale(1.1);
}

.color-selected {
  border-color: #0052cc;
  background: #f0f7ff;
}

.color-span {
  display: inline-block;
  width: 22px;
  height: 22px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.color-span:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.custom-color-picker :deep(.el-color-picker__trigger) {
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.custom-color-picker :deep(.el-color-picker__trigger:hover) {
  border-color: #0052cc;
}

/* 级别输入区域 */
.level-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.custom-input-number {
  width: 200px;
}

.custom-input-number :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

.custom-input-number :deep(.el-input-number__decrease),
.custom-input-number :deep(.el-input-number__increase) {
  color: #0052cc;
}

.custom-input-number :deep(.el-input-number__decrease:hover),
.custom-input-number :deep(.el-input-number__increase:hover) {
  background: #f0f7ff;
  color: #003d99;
}

.level-tips {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
}

/* 预览区域 */
.preview-item {
  margin-bottom: 24px;
}

.preview-wrapper {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
  border-top: 1px solid #e4e7ed;
}

.footer-right {
  display: flex;
  gap: 12px;
}

.submit-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #0052cc;
  border-color: #0052cc;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #ecf5ff;
  border-color: #0052cc;
  color: #0052cc;
}

.delete-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #f56c6c;
  border-color: #f56c6c;
  font-weight: 500;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background: #f78989;
  border-color: #f78989;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .custom-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 16px 20px;
  }

  .custom-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .form-container {
    padding: 16px;
  }

  .form-item {
    margin-bottom: 16px;
  }

  .color-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .color-palette {
    width: 100%;
    justify-content: flex-start;
  }

  .level-input-wrapper {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .custom-input-number {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }

  .footer-right {
    width: 100%;
    flex-direction: column;
  }

  .submit-btn,
  .cancel-btn,
  .delete-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .custom-dialog :deep(.el-dialog) {
    width: 98% !important;
    margin: 2vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 12px 16px;
  }

  .custom-dialog :deep(.el-dialog__title) {
    font-size: 14px;
  }

  .form-container {
    padding: 12px;
  }

  .color-palette {
    gap: 6px;
  }

  .color-span {
    width: 20px;
    height: 20px;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 动画效果 */
.form-container {
  transition: all 0.3s ease;
}

.color-item,
.color-span {
  transition: all 0.3s ease;
}

/* 主题色变量 */
:root {
  --primary-color: #0052cc;
  --primary-hover: #003d99;
  --primary-light: #f0f7ff;
  --border-color: #e4e7ed;
  --text-color: #303133;
  --bg-color: #f8f9fa;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-color-picker__panel) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
